﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iMapa.Backend.ActionPlugin;
using ActionPluginAPI;
using System.Media;

namespace iMapa.Backend
{
    public class ExecutionQueue
    {
        private Queue<InteractObject> q= new Queue<InteractObject>();
        private Dictionary<InteractObject,Decimal> d= new Dictionary<InteractObject,Decimal>();

        SoundPlayer player = new SoundPlayer(Properties.Resources.alert);

        public ExecutionQueue()
        {

        }

        public void Reset() {
            d.Clear();
            q.Clear();
        }

        internal void Enqueue(InteractObject io)
        {
            int fps = CameraInput.getInstance().getFps();
            int queueLength = fps == 0 ? 15 : 2*fps;
            int countToExecAction = fps == 0 ? 7 : fps;
            q.Enqueue(io);
            IncrementCount(io);
            if (q.Count > queueLength)
            {
                InteractObject dio=q.Dequeue();
                DecrementCount(dio);
            }
            if (Count(io) >= countToExecAction)
            {
                IActionPlugin plugin = PluginHandler.getInstance().GetPluginsByName(io.ActionType);
                player.Stop();
                player.Play(); 
                plugin.Execute(io.ActionParams);
                Reset();
            }

        }

        private void IncrementCount(InteractObject io)
        {
            if (io != null)
            {

                if (d.ContainsKey(io))
                {
                    Decimal o;
                    d.TryGetValue(io, out o);
                    o += 1;
                    d.Remove(io);
                    d.Add(io, o);

                }
                else
                {
                    d.Add(io, 1);
                }
            }
        }

        private void DecrementCount(InteractObject io)
        {
            if (io != null)
            {

                Decimal o;
                d.TryGetValue(io, out o);
                o = o < 0 ? 0 : o - 1;
                d.Remove(io);
                d.Add(io, o);
            }
        }

        private void ResetCount(InteractObject io)
        {
            if (io != null)
            {

                Decimal o;
                d.TryGetValue(io, out o);
                o = 0;
                d.Remove(io);
                d.Add(io, o);
            }
        }

        private Decimal Count(InteractObject io)
        {
            if (io != null)
            {

                Decimal o;
                d.TryGetValue(io, out o);
                return o == null ? 0 : o;
            }
            return 0;
        }

    }
}
